<template>
  <div class="network-basic">
    <a-form :model="formState" layout="vertical">
      <a-card title="网络模式" :bordered="false">
        <a-form-item name="networkMode">
          <a-radio-group v-model:value="formState.networkMode" button-style="solid">
            <a-radio-button value="dhcp">DHCP</a-radio-button>
            <a-radio-button value="static">静态IP</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <template v-if="formState.networkMode === 'static'">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="IP地址" name="ipAddress" :rules="[{ required: true, message: '请输入IP地址' }]">
                <a-input v-model:value="formState.ipAddress" placeholder="192.168.1.100" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="子网掩码" name="subnetMask" :rules="[{ required: true, message: '请输入子网掩码' }]">
                <a-input v-model:value="formState.subnetMask" placeholder="255.255.255.0" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="默认网关" name="gateway" :rules="[{ required: true, message: '请输入默认网关' }]">
                <a-input v-model:value="formState.gateway" placeholder="192.168.1.1" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="首选DNS" name="primaryDNS" :rules="[{ required: true, message: '请输入首选DNS' }]">
                <a-input v-model:value="formState.primaryDNS" placeholder="8.8.8.8" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="备选DNS" name="secondaryDNS">
            <a-input v-model:value="formState.secondaryDNS" placeholder="8.8.4.4" />
          </a-form-item>
        </template>
      </a-card>

      <div style="margin-top: 16px">
        <a-space>
          <a-button type="primary" @click="handleSubmit" :loading="loading">保存设置</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-space>
      </div>
    </a-form>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import request from '@/utils/request';

export default defineComponent({
  name: 'NetworkBasic',
  setup() {
    const defaultSettings = {
      networkMode: 'dhcp',
      ipAddress: '',
      subnetMask: '',
      gateway: '',
      primaryDNS: '',
      secondaryDNS: ''
    };

    const formState = reactive({ ...defaultSettings });
    const loading = ref(false);

    const getNetworkConfig = async () => {
      try {
        loading.value = true;
        const response = await request.get('/v1/network/config');

        if (response.data) {
          // 获取默认接口配置
          const defaultInterface = response.data.defaultInterface;
          const interfaceConfig = response.data.interfaces[defaultInterface];

          if (interfaceConfig) {
            // 更新表单状态
            formState.networkMode = interfaceConfig.dhcp ? 'dhcp' : 'static';

            if (!interfaceConfig.dhcp) {
              formState.ipAddress = interfaceConfig.ipAddress;
              formState.subnetMask = interfaceConfig.netmask;
              formState.gateway = interfaceConfig.gateway;
            }

            // 设置DNS配置
            formState.primaryDNS = response.data.primaryDNS || '';
            formState.secondaryDNS = response.data.secondaryDNS || '';
          }
        }
      } catch (error) {
        console.error('获取网络配置失败:', error);
        message.error('获取网络配置失败，请刷新页面重试');
      } finally {
        loading.value = false;
      }
    };

    const handleSubmit = async () => {
      try {
        loading.value = true;

        // 获取网络配置
        const response = await request.get('/v1/network/config');
        const defaultInterface = response.data?.defaultInterface || 'eth0';

        // 构建请求数据
        const networkConfig = {
          mode: formState.networkMode
        };

        // 静态IP模式下需要添加IP配置
        if (formState.networkMode === 'static') {
          networkConfig.ipv4 = {
            address: formState.ipAddress,
            netmask: formState.subnetMask,
            gateway: formState.gateway,
            dns: [formState.primaryDNS]
          };

          if (formState.secondaryDNS) {
            networkConfig.ipv4.dns.push(formState.secondaryDNS);
          }
        } else {
          // DHCP模式下，如果配置了DNS，也需要添加
          if (formState.primaryDNS || formState.secondaryDNS) {
            networkConfig.ipv4 = {
              dns: []
            };
            if (formState.primaryDNS) {
              networkConfig.ipv4.dns.push(formState.primaryDNS);
            }
            if (formState.secondaryDNS) {
              networkConfig.ipv4.dns.push(formState.secondaryDNS);
            }
          }
        }

        // 发送更新请求
        const updateResponse = await request.put(`/v1/network/interfaces/${defaultInterface}`, networkConfig);

        if (updateResponse.data?.requires_reboot) {
          message.success('网络设置已保存，需要重启设备以使配置生效');
        } else {
          message.success('网络设置已保存');
        }
      } catch (error) {
        console.error('保存网络设置失败:', error);
        message.error('保存失败: ' + (error.response?.data?.error || '请重试'));
      } finally {
        loading.value = false;
      }
    };

    const handleReset = () => {
      Object.assign(formState, defaultSettings);
      message.info('已重置为默认设置');
    };

    // 组件挂载时获取网络配置
    onMounted(() => {
      getNetworkConfig();
    });

    return {
      formState,
      loading,
      handleSubmit,
      handleReset
    };
  }
});
</script>

<style scoped>
.network-basic {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
</style>
